<template>
	<div>
		<el-card class="box-card">
			<div class="text item">
				所属项目： {{projectInfo.origin.name}}
			</div>
		</el-card>

		<el-form style="margin-top: 1vh;" ref="reform" :model="advForm" label-position="top" :rules="advFormRules"
			:validate-on-rule-change="false">
			<el-card class="box-card">
				<template #header>
					<div class="card-header">
						<span>广告设置</span>
					</div>
				</template>
				<el-form-item label="广告名称" label-width="140px" prop="name">
					<el-input v-model="advForm.name" style="width: 50%;" />
				</el-form-item>

				<el-form-item label="来源" label-width="140px" prop="source">
					<el-input v-model="advForm.source" style="width: 50%;" />
					<el-text>需填写广告主公司名称或者品牌名称中具有代表性的核心词汇，不得使用通用的描述词汇。示范案例：xx防水补漏，违规案例：防水补漏</el-text>
				</el-form-item>
				<el-form-item label="广告评论" label-width="140px" prop="is_comment_disable">
					<el-radio-group v-model="advForm.is_comment_disable" style="width: 50%;">
						<el-radio-button v-for="item in generation_list" :key="item.value" :label="item.value"
							>
							{{ item.label }}
						</el-radio-button>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="品牌名称" label-width="140px" prop="brand_info">
					<el-select v-model="selectedBrand" @change="brandSelectChange" style="width: 40%;"
						:clearable="true">
						<el-option v-for="brand in brand_list" :key="brand.cdp_brand_id" :label="brand.cdp_brand_name"
							:value="brand" />
					</el-select>
				</el-form-item>
				<el-form-item label="抖音号" label-width="140px" prop="aweme_id" v-if="false">
					<el-select v-model="advForm.native_setting.aweme_id" style="width: 40%;" :clearable="true">
						<el-option v-for="(item,index) in aweme_list" :key="index" :label="item.label"
							:value="item.value" />
					</el-select>
				</el-form-item>
			</el-card>

			<el-card class="box-card" style="margin-top: 1vh;">
				<template #header>
					<div class="card-header">
						<span>广告素材</span>
					</div>
				</template>
				<el-form-item  prop="batch_number">
					<el-switch v-model="batch" active-text="批量生成广告" inactive-text="" style="margin-right: 1vh;" />
					<template v-if="batch">单条广告的素材数：<el-input type="number" style="width: 10vh"
							v-model="advForm.batch_number" /></template>
					</el-form-item>
				<el-form-item label="基础素材" prop="materia">
					<CreateVideoList @receive="onReceiveVideo" :extensions="extensions" />
					<div style="width: 1vh;"></div>
					<OceanEnginelImg ref="materiaImg" name="materiaImg" @receive="onReceiveImage" listParam="" :advertiser_id="projectInfo.origin.advertiser_id.toString()" />
					<div style="width: 1vh;"></div>
					<OceanEngineCarousel ref="materiaCarousel" @receive="onReceiveCarousel"  :advertiser_id="projectInfo.origin.advertiser_id.toString()"></OceanEngineCarousel>
				</el-form-item>

				<el-tabs v-model="materialActive" type="border-card" style="margin-bottom: 1vh;">
					<el-tab-pane label="视频" name="videos">
						<el-empty v-if="materialVideoList.length<=0" description="暂无数据" />
						<el-image v-for="(item,index) in materialVideoList" :preview-src-list="[item.url]"
							:initial-index="0" style="width: 120px; height: 200px;margin-right: 1vh;" :src="item.url"
							fit="cover" />

					</el-tab-pane>
					<el-tab-pane label="图片" name="images">
						<el-empty v-if="materialImageList.length<=0" description="暂无数据" />
						<el-image v-for="(item,index) in materialImageList" :preview-src-list="[item.url]"
							:initial-index="0" style="width: 120px; height: 200px;margin-right: 1vh;" :src="item.url"
							fit="cover" />
					</el-tab-pane>
					<el-tab-pane label="图文" name="carousels">
						<el-empty v-if="materialCarouselList.length<=0" description="暂无数据" />
						<el-image v-for="(item,index) in materialCarouselList" :preview-src-list="[item.images[0].url]"
							:initial-index="0" style="width: 120px; height: 200px;margin-right: 1vh;" :src="item.images[0].url"
							fit="cover" />
					</el-tab-pane>
				</el-tabs>
				<el-form-item label="文案素材" prop="title_material_list">
					<div style="width:100%;margin-bottom: 1vh;"
						v-for="(item,index) in advForm.promotion_materials.title_material_list">
						<el-input style="width:80%;" maxlength="30" minlength="5" placeholder="请输入标题(5-30)" show-word-limit type="text"
							v-model="item.title" /><el-button @click="removeTitleMaterialList(index)"
							v-if="advForm.promotion_materials.title_material_list.length>1 ? true : false"
							icon="DeleteFilled" style="margin-left: 1vh;" />
					</div>
					<el-button-group style="width:100%;">
						<el-button style="width: 80%;border: 1px dashed var(--el-border-color);"
							@click="addTitleMaterialList">+新增</el-button>
						<el-button type="primary">批量添加</el-button>
					</el-button-group>

				</el-form-item>
				<el-form-item label="行动号召" label-width="140px" prop="call_to_action_buttons">
					<el-input v-model="inputText" style="width: 60%;margin-right: 1vh;"
						placeholder="最多10个行动号召，每个2-4个字，可空格分隔" @keyup.enter="handleEnter"><template #append><el-button
								@click="handleEnter">添加(回车键)</el-button></template></el-input>
					<el-checkbox-group v-model="advForm.promotion_materials.intelligent_generation">
						<el-checkbox label="开启智能生成" value="ON" />
					</el-checkbox-group>
					<el-card style="margin-top:1vh;width:100%" shadow="never"
						v-if="advForm.promotion_materials.call_to_action_buttons.length>0">
						<template #header>
							已选（{{ advForm.promotion_materials.call_to_action_buttons.length }}/10）
							<el-button type="text" style="float: right;"
								@click="clear_call_to_action_buttons">清除</el-button>
						</template>
						<el-tag style="margin-right: 1vh;"
							v-for="(item, index) in advForm.promotion_materials.call_to_action_buttons" :key="index"
							closable type="primary" @close="removeItem(index)">
							{{ item }}
						</el-tag>
					</el-card>

				</el-form-item>
				<!--
				<el-form-item label="原生锚点" label-width="140px" prop="native_setting">
					<el-radio-group v-model="advForm.native_setting.anchor_related_type" style="width: 50%;">
						<el-radio-button v-for="item in anchor_related_type_list" :key="item.value" :label="item.value">
							{{ item.label }}
						</el-radio-button>
					</el-radio-group>
				</el-form-item>
				-->
				

				<el-form-item label="小程序链接" label-width="140px" prop="url">
					<el-input v-model="advForm.promotion_materials.mini_program_info.url" style="width: 50%;">
						<template #append><el-button type="primary" @click="openGameDialog">选择已有</el-button></template>
					</el-input>

				</el-form-item>
				<el-form-item label="备用网页链接" label-width="140px" prop="external_url_material_list">
					<el-select v-model="advForm.promotion_materials.external_url_material_list[0]" style="width: 40%;">
						<el-option v-for="(item,index) in site_list" :key="index" :label="item.label"
							:value="item.value" />
					</el-select>
				</el-form-item>
				
			
			</el-card>
			<el-card class="box-card" style="margin-top: 1vh;">
				<template #header>
					<div class="card-header">
						<span>产品信息</span>
					</div>
				</template>
				<el-form-item label="产品名称" label-width="140px" prop="product_info_titles">
					<el-input  v-model="advForm.promotion_materials.product_info.titles[0]" style="width: 50%;"  maxlength="20"/>
					</el-form-item>
				<el-form-item label="产品图片" label-width="140px" prop="product_info_images">
					<OceanEnginelImg ref="productImg" name="productImg" @receive="onReceiveProductInfoImage" type="CREATIVE_IMAGE_MODE_DISPLAY_PRODUCT" :advertiser_id="projectInfo.origin.advertiser_id.toString()" />
					<el-card style="margin-top:1vh;width:100%" shadow="never"
						v-if="materialProductList.length>0">
						<template #header>
							已选（{{ materialProductList.length }}/10）
							<el-button type="text" style="float: right;"
								@click="clear_call_to_action_buttons">清除</el-button>
						</template>
						<el-image v-for="(item,index) in materialProductList" :preview-src-list="[item.url]"
							:initial-index="0" style="width: 108px; height: 108px;margin-right: 1vh;" :src="item.url"
							fit="cover" />
					</el-card>
					</el-form-item>
					
				<el-form-item label="产品卖点" label-width="140px" prop="selling_points">
					<el-input v-model="inputSellingPoints" style="width: 60%;margin-right: 1vh;"
						placeholder="最多10个产品卖点，每个6-9个字，可空格分隔" @keyup.enter="sellingPointsHandleEnter"><template #append><el-button
								@click="sellingPointsHandleEnter">添加(回车键)</el-button></template></el-input>
					
					<el-card style="margin-top:1vh;width:100%" shadow="never"
						v-if="advForm.promotion_materials.product_info.selling_points.length>0">
						<template #header>
							已选（{{ advForm.promotion_materials.product_info.selling_points.length }}/10）
							<el-button type="text" style="float: right;"
								@click="clear_selling_points">清除</el-button>
						</template>
						<el-tag style="margin-right: 1vh;"
							v-for="(item, index) in advForm.promotion_materials.product_info.selling_points" :key="index"
							closable type="primary" @close="removeSellingPointsItem(index)">
							{{ item }}
						</el-tag>
					</el-card>
				
				</el-form-item>
			</el-card>
			<el-card class="box-card" style="margin-top: 1vh;">
				<template #header>
					<div class="card-header">
						<span>广告预算与出价</span>
					</div>
				</template>
				<div class="box-card-bar">
					<el-text v-if="projectInfo.origin.delivery_setting.bid_type"><el-text
							class="title">竞价策略：</el-text><el-text class="info"
							tag="b">{{enums[projectInfo.origin.delivery_setting.bid_type]}}</el-text></el-text>
					<el-text v-if="projectInfo.origin.optimize_goal.external_action"><el-text
							class="title">优化目标：</el-text><el-text class="info"
							tag="b">{{enums[projectInfo.origin.optimize_goal.external_action]}}</el-text></el-text>
					<el-text v-if="projectInfo.origin.optimize_goal.deep_external_action"><el-text
							class="title">深度优化目标：</el-text><el-text class="info"
							tag="b">{{enums[projectInfo.origin.optimize_goal.deep_external_action]}}</el-text></el-text>
					<el-text v-if="projectInfo.origin.delivery_setting.deep_bid_type"><el-text
							class="title">深度优化方式：</el-text><el-text class="info"
							tag="b">{{enums[projectInfo.origin.delivery_setting.deep_bid_type]}}</el-text></el-text>
					<el-text v-if="projectInfo.origin.pricing"><el-text class="title">计费方式：</el-text><el-text
							class="info" tag="b">{{enums[projectInfo.origin.pricing]}}</el-text></el-text>
				</div>
				
				<el-form-item
					:label=" projectInfo.origin.delivery_setting.budget_mode=='BUDGET_MODE_DAY' ? '日预算' :'预算' "
					label-width="140px"
					prop="budget"
					v-if="projectInfo.origin.delivery_mode!='PROCEDURAL' && projectInfo.origin.delivery_type!='DURATION'">
					<el-input type="number" style="width: 50%;" v-model="advForm.budget"></el-input>
				</el-form-item>
				
				<el-form-item label="ROI系数" label-width="140px"
				prop="roi_goal"
					v-if="projectInfo.origin.delivery_mode !='PROCEDURAL' && (projectInfo.origin.value_optimized_type  == 'VALUE' || (projectInfo.origin.landing_type =='MICRO_GAME' && projectInfo.origin.ad_type =='ALL' && projectInfo.origin.delivery_mode=='MANUAL' && projectInfo.origin.optimize_goal.external_action=='AD_CONVERT_TYPE_ACTIVE' && projectInfo.origin.optimize_goal.deep_external_action=='AD_CONVERT_TYPE_LT_ROI'))">
					<el-input type="number" style="width: 50%;" v-model="advForm.roi_goal"></el-input>
					<el-text size="small" style="width:100%">在本次投放活动中，ROI系数 = 广告投放收益/广告投放成本</el-text>
				</el-form-item>
				
				<el-form-item label="目标转化出价" label-width="140px" prop="cpa_bid" style="width: 83%;"
					v-if="['PRICING_OCPM','PRICING_OCPC'].includes(projectInfo.origin.pricing) && projectInfo.origin.project_custom!='ON' && projectInfo.origin.bid_type!='NO_BID' && projectInfo.origin.delivery_mode!='PROCEDURAL' && projectInfo.origin.value_optimized_type !='VALUE' && projectInfo.origin.delivery_type !='DURATION' && projectInfo.origin.delivery_type !='DURATION' && !(projectInfo.origin.landing_type =='MICRO_GAME' && projectInfo.origin.ad_type =='ALL' && projectInfo.origin.optimize_goal.external_action=='AD_CONVERT_TYPE_ACTIVE' && projectInfo.origin.optimize_goal.deep_external_action=='AD_CONVERT_TYPE_LT_ROI') ">
					<el-input type="number" v-model="advForm.cpa_bid" style="width: 50%;">
						<template #append><el-button type="primary" @click="openBidSuggest">建议出价</el-button></template>
					</el-input>
				</el-form-item>

				<el-form-item label="点击/展示出价" label-width="140px" prop="bid" style="width: 83%;"
					v-if="['PRICING_CPM','PRICING_CPC'].includes(projectInfo.origin.pricing)">
					<el-input type="number" v-model="advForm.bid" style="width: 50%;">

					</el-input>
				</el-form-item>

				<el-form-item label="深度优化出价" label-width="140px" prop="deep_cpabid" style="width: 83%;"
					v-if="projectInfo.origin.bid_type!='NO_BID' && projectInfo.origin.delivery_mode!='PROCEDURAL' && (projectInfo.origin.delivery_setting.deep_bid_type=='DEEP_BID_MIN' || projectInfo.origin.delivery_setting.deep_external_action=='AD_CONVERT_TYPE_PHONE_CONNECT')">
					<el-input type="number" v-model="advForm.deep_cpabid" style="width: 50%;">

					</el-input>
				</el-form-item>
				
			</el-card>
		</el-form>
		<el-dialog v-model="dialogGameVisible" :before-close="closeGameDialog" title="选择已有小程序链接">
			<el-table :data="game_list" style="width: 100%">
				<el-table-column prop="instance_id" label="小程序资产id" width="400"></el-table-column>
				<el-table-column prop="name" label="小程序名称" width="400"></el-table-column>
				<el-table-column label="操作">
					<template #default="scope">
						<el-button type="primary" @click="selectGame(scope.row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>

		<el-dialog v-model="dialogBidSuggestVisible" :before-close="closeBidSuggest" title="建议出价" width="400px">
			<p>根据您近7天的素材质量评估结果，建议出价如下:</p>
			<el-row class="suggest-row">
				<el-col :span="12" class="suggest-text">竞争力超过 90% 的计划</el-col>
				<el-col :span="6" class="suggest-price">{{ suggestInfo.bid_high_90 }} 元</el-col>
				<el-col :span="4" class="suggest-action">
					<el-button type="text" @click="adoptSuggestion(suggestInfo.bid_high_90)">采纳</el-button>
				</el-col>
			</el-row>
			<el-row class="suggest-row">
				<el-col :span="12" class="suggest-text">竞争力超过 50% 的计划</el-col>
				<el-col :span="6" class="suggest-price">{{ suggestInfo.bid_high_50 }} 元</el-col>
				<el-col :span="4" class="suggest-action">
					<el-button type="text" @click="adoptSuggestion(suggestInfo.bid_high_50)">采纳</el-button>
				</el-col>
			</el-row>
			<el-row class="suggest-row">
				<el-col :span="12" class="suggest-text">竞争力超过 30% 的计划</el-col>
				<el-col :span="6" class="suggest-price">{{ suggestInfo.bid_high_30 }} 元</el-col>
				<el-col :span="4" class="suggest-action">
					<el-button type="text" @click="adoptSuggestion(suggestInfo.bid_high_30)">采纳</el-button>
				</el-col>
			</el-row>
		</el-dialog>
	</div>


</template>
<script lang="ts" setup>
	import { ref, reactive } from 'vue'
	import { getHugeInfo } from '@/api/qmAccessTokens'
	import JSONBIG from 'json-bigint'
	import { useUserStore } from '@/pinia/modules/user'
	import CustomPic from '@/components/customPic/index.vue'
	import { getQmGameListList } from '@/api/qmGameList'
	import { RuleTester } from 'eslint'
	import { setConfig, CreateMaterialList, CreateVideoList } from '@bytedance-ad/mui-vue3'
	import OceanEnginelImg from '@/components/chooseImg/oceanengineImg.vue'
	import OceanEngineCarousel from '@/components/chooseImg/oceanengineCarousel.vue'
	import { useRouter, useRoute } from 'vue-router'
	import { rpcGet } from '@/api/rpc'
	import { enums } from '@/utils/enums.js'
	const router = useRouter()
	const useRoutes = useRoute()
	const delivery_mode = useRoutes.query.delivery_mode
	const extensions = ref({
		max: 10,
	})

	const props = defineProps({
		projectInfo: {
			type: Object,
			default: null,
		}
	})
	setTimeout(() => {
		console.log(props.projectInfo.origin)
	}, 1000)
	const advertiser_id = props.projectInfo.origin.advertiser_id.toString()
	const project_id = props.projectInfo.origin.project_id.toString()
	const batch = ref(false)
	const materialActive = ref("videos")
	const materialVideoList = ref([])
	const materialImageList = ref([])
	const materialCarouselList = ref([])
	const onReceiveImage = (value) => {
		materialActive.value = "images"
		materialImageList.value = value
	};
	const onReceiveVideo = (value) => {
		// 选中的素材视频
		materialActive.value = "videos"
		materialVideoList.value = value.video_material_list
		materialVideoList.value.forEach(item => {
			item.videoUrl = item.url
			item.url = item.imageUrl
		})
	};
	const onReceiveCarousel = (value) => {
		materialActive.value = "carousels"
		console.log(value)
		materialCarouselList.value = value
	}
	const materialProductList = ref([])
	const onReceiveProductInfoImage = (value) => {
		materialProductList.value = value
	}
	
	
	
	setConfig({
		appId: '1806716056834058', // 必填，否则无法使用MUI, 可在后台管理系统https://open.oceanengine.com/developer/admin/ad_list获取
		host: import.meta.env.VITE_BASE_API,
		params: { // 可选，自定义每次请求的参数
			advertiser_id: advertiser_id,
		},
		apis: {
			getImages: '/openApi/file/image/get/', //获取图片
			uploadImage: '/openApi/file/image/ad/', //上传图片
			getVideos: '/openApi/file/video/get/',  //获取视频
			uploadVideo: '/openApi/file/video/ad/', //上传视频
			getAudio: '/openApi/file/audio/get/',  //获取音频
			uploadAudio: '/openApi/file/audio/ad/', //上传音频
			getCarousel: '/openApi/carousel/list/',//获取图文素材
			uploadCarousel: '/openApi/carousel/create/',//上传图文
		}
	})



	const anchor_related_type_list = reactive([
		{
			value: 'AUTO',
			label: '自动生成'
		},
		{
			value: 'OFF',
			label: '不启用',
		},
	])

	const generation_list = reactive([
		{
			value: 'ON',
			label: '开启',
		},
		{
			value: 'OFF',
			label: '关闭',
		},
	])

	const operation_list = reactive([
		{
			value: 'ENABLE',
			label: '开启',
			disabled: false
		},
		{
			value: 'DISABLE',
			label: '关闭',
			disabled: false
		},
	])

	const title_material_list_default =
		{
			"title": "",
		}
	const advForm = ref({
		"advertiser_id": advertiser_id,
		"project_id": project_id,
		"name": "",
		"operation": "DISABLE",
		"batch_number": 0,
		"promotion_materials": {
			"video_material_list": [
			],
			"image_material_list": [
			],
			"title_material_list": [
				
			],
			"product_info": {
				"titles":[],
				"image_ids":[],
				"selling_points":[]
			},
			"call_to_action_buttons": [
			],
			"anchor_material_list": [
			],
			"external_url_material_list":[],//普通落地页链接素材
			"mini_program_info": {
				"url": "",
			},
			"carousel_material_list": [],
			"dynamic_creative_switch": "OFF",
			"intelligent_generation": "OFF",
			"blue_flow_material_recommend": "OFF"//是否开启系统推荐图文
		},
		/*"native_setting": {
			"aweme_setting_type": "SINGLE",
			"aweme_id": "",
			"anchor_related_type": "OFF"
		},*/
		//"budget_mode": "BUDGET_MODE_TOTAL", //预算类型
		"budget": 0,
		"bid": 0,
		"roi_goal":0,
		"cpa_bid": 0,
		"deep_cpabid": 0,
		"source": "",
		"is_comment_disable": "ON",
		"brand_info": "",
		"materia": "",//验证专用
	})
	const validator = (rule : any, value : any, callback : any) => {

		switch (rule.field) {
			case "url":
				if (advForm.value.promotion_materials.mini_program_info.url == "") {
					callback(new Error('选择小程序链接'))
				}
				break;
			case "external_url_material_list ":
				if (advForm.value.promotion_materials.external_url_material_list.length<=0) {
					callback(new Error('选择落地页'))
				}
				break;
			case "aweme_id":
				if (advForm.value.native_setting.aweme_id == "") {
					callback(new Error('选择抖音号'))
				}
				break;
			case "call_to_action_buttons":
				if (advForm.value.promotion_materials.call_to_action_buttons.length <= 0) {
					callback(new Error('请输入行动号召'))
				}
				break;
			case "materia":
				if (materialVideoList.value.length + materialImageList.value.length <= 0) {
					callback(new Error('请选择一个视频或者图片素材'))
				}
				break;
			case "budget":
				if(["PRICING_CPM","PRICING_CPC"].includes(props.projectInfo.origin.pricing)){
					if(value<100)
						callback(new Error('请输入预算，不少于100元，不超过9999999.99元'))
				}
				if(["PRICING_OCPM","PRICING_OCPC"].includes(props.projectInfo.origin.pricing)){
					if(props.projectInfo.origin.delivery_setting.bid_type=="NO_BID"){
						if(value<100){
							callback(new Error('请输入预算，不少于100元，不超过9999999.99元'))
						}
					}else{
						if(value<300)
							callback(new Error('请输入预算，不少于300元，不超过9999999.99元'))
						}
				}
				break;
			case "roi_goal":
				if(value>5 || value<1)
					callback(new Error('请输入ROI系数，大于0，不超过5'))
				break;
			case "cpa_bid":
				if(value>1 || value<0.01)
					callback(new Error('请输入广告出价，不少于0.01元，不超过1元'))
				break;
			case "batch_number":
					if(batch.value && (value<1 || value>100))
						callback(new Error('请设置单条广告的素材数'))
					break;
			case "title_material_list":
					if(advForm.value.promotion_materials.title_material_list.length<=0)
						callback(new Error('至少添加一条文案素材'))
					advForm.value.promotion_materials.title_material_list.forEach(item=>{
						if(item.title.length<5)
							callback(new Error('长度为5-30个字, 两个英文字符占1位'))
					})
					break;
			case "product_info_titles":
				   if(!advForm.value.promotion_materials.product_info.titles[0] || advForm.value.promotion_materials.product_info.titles[0].length>20){
					   callback(new Error('请填写产品名称，长度为1-20'))
				   }	
			break;
			case "product_info_images":
				if (materialProductList.value.length <= 0) {
					callback(new Error('请选择产品图片'))
				}
			break;
			case "selling_points":
				if(advForm.value.promotion_materials.product_info.selling_points.length<1){
					callback(new Error('至少输入一个产品卖点'))
				}
			break;
			
		}
		callback()
	}

	const advFormRules = ref({
		name: [
			{ required: true, message: '请输入广告名称', trigger: 'blur' }
		],
		source: [
			{ required: true, message: '请输入来源', trigger: 'blur' }
		],
		brand_info: [
			{ required: true, message: '选择品牌', trigger: 'blur' }
		],
		materia: [
			{ required: true, validator: validator, trigger: 'blur' }
		],
		is_comment_disable: [
			{ required: true, message: '选择是否开启广告评论', trigger: 'blur' }
		],
		call_to_action_buttons: [
			{ required: true, validator: validator, trigger: 'blur' },
		],
		native_setting: [
			{ required: true, message: '选择原生设置', trigger: 'blur' }
		],
		url: [
			{ required: true, validator: validator, trigger: 'blur' }
		],
		external_url_material_list: [
			{ required: true, validator: validator, trigger: 'blur' }
		],
		aweme_id: [
			{ required: true, validator: validator, trigger: 'blur' }
		],
		budget:[
			{ required: true, validator: validator, trigger: 'blur' }
		],
		roi_goal:[
			{ required: true, validator: validator, trigger: 'blur' }
		],
		cpa_bid:[
			{ required: true, validator: validator, trigger: 'blur' }
		],
		batch_number:[
			{ required: true, validator: validator, trigger: 'blur' }
		],
		title_material_list: [
			{ required: true, validator: validator, trigger: 'blur' }
		],
		product_info_titles:[
			{ required: true, validator: validator, trigger: 'blur' }
		],
		product_info_images:[
			{ required: true, validator: validator, trigger: 'blur' }
		],
		selling_points:[
			{ required: true, validator: validator, trigger: 'blur' }
		],
	})

	//抖音号
	const aweme_list = ref([])
	const getAwemeList = () => {
		const params = {
			advertiserId: advertiser_id,
			platformId: 1
		}
		getHugeInfo({ type: 'getAwemeList', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				aweme_list.value = []
				const arr = JSONBIG.parse(res.data.info)
				arr.forEach(item => {
					aweme_list.value.push({
						value: item.aweme_id,
						label: item.aweme_name
					})
				})
			}
		})
	}
	getAwemeList()

	// 获取已有小程序链接
	const dialogGameVisible = ref(false)
	// 游戏列表
	const game_list = ref([])
	const getGameList = () => {
		const params = {
			advertiserId: advertiser_id,
			platformId: 1
		}
		getHugeInfo({ type: 'getGames', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				game_list.value = []
				const arr = JSONBIG.parse(res.data.info)
				arr.forEach(item => {
					game_list.value.push({
						instance_id: item.instance_id,
						name: item.name
					})
				})
			}
		})
	}
	// 游戏详情
	const getGameDetail = (instanceId) => {
		const params = {
			advertiserId: advertiser_id,
			platformId: 1,
			instanceId: instanceId,
		}
		getHugeInfo({ type: 'getGameDetail', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				const arr = JSONBIG.parse(res.data.info)
				var link = arr[0].link
				//写入 小程序链接中
				advForm.value.promotion_materials.mini_program_info.url = link
				
			}
		})
	}
	const openGameDialog = () => {
		dialogGameVisible.value = true
		getGameList()
		//console.log(game_list)
	}
	const selectGame = (row) => {
		dialogGameVisible.value = false;
		getGameDetail(row.instance_id)

	}
	const closeGameDialog = () => {
		dialogGameVisible.value = false
	}

	// 获取橙子建站站点列表
	// 备用网页链接
	const site_list = ref([])
	const getSiteList = () => {
		const params = {
			advertiserId: advertiser_id,
			platformId: 1
		}
		getHugeInfo({ type: 'getSiteList', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				site_list.value = []
				const arr = JSONBIG.parse(res.data.info)
				arr.forEach(item => {
					site_list.value.push({
						value: item.link,
						label: item.name,
					})
				})
			}
		})
	}

	getSiteList()



	// 建议出价
	const dialogBidSuggestVisible = ref(false)
	const openBidSuggest = () => {
		dialogBidSuggestVisible.value = true
	}
	const closeBidSuggest = () => {
		dialogBidSuggestVisible.value = false
	}
	const useSuggestion = (price) => {
		console.log(price)
	}
	// 查询建议出价
	const suggestInfo = {
		bid_high_30: 0,
		bid_high_50: 0,
		bid_high_90: 0
	}
	const getBidsSuggest = () => {
		const params = {
			advertiserId: advertiser_id,
			projectId: project_id,
			platformId: 1,
			pricing: props.projectInfo.origin.pricing,
			externalAction: props.projectInfo.origin.optimize_goal.external_action,
		}
		getHugeInfo({ type: 'getBidsSuggest', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				const arr = JSONBIG.parse(res.data.info)
				suggestInfo.bid_high_30 = arr.bid_high_30
				suggestInfo.bid_high_50 = arr.bid_high_50
				suggestInfo.bid_high_90 = arr.bid_high_90
			}
		})
	}
	getBidsSuggest()



	// 获取品牌信息
	const brand_list = ref([])
	const getBrandList = () => {
		const params = {
			advertiserId: advertiser_id,
			platformId: 1,
		}
		getHugeInfo({ type: 'getBrandList', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				brand_list.value = []
				const arr = JSONBIG.parse(res.data.info)
				arr.forEach(item => {
					brand_list.value.push({
						cdp_brand_name: item.cdp_brand_name,
						cdp_brand_id: item.cdp_brand_id,
						brand_name_id: item.brand_name_id,
						ecom_brand_id: item.ecom_brand_id,
					})
				})
			}
		})
	}
	getBrandList()

	const selectedBrand = ref(null);
	const brandSelectChange = () => {
		if (selectedBrand.value) {
			advForm.value.brand_info = {
				yuntu_category_id: 0,
				cdp_brand_id: selectedBrand.value.cdp_brand_id,
				ecom_brand_id: selectedBrand.value.ecom_brand_id,
				brand_name_id: selectedBrand.value.brand_name_id,
				cdp_brand_name: selectedBrand.value.cdp_brand_name,
			};
		} else {
			advForm.value.brand_info = ""
		}
	}

	// 查询推广卡片推荐内容
	// 产品卖点 textType: "PROMOTION",
	const promotion_list = ref([])
	const getPromotionList = () => {
		const params = {
			advertiserId: advertiser_id,
			textType: "PROMOTION",
			platformId: 1,
		}
		getHugeInfo({ type: 'getPromotionList', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				promotion_list.value = []
				const arr = JSONBIG.parse(res.data.info)
				promotion_list.value = arr.list
			}
		})
	}
	getPromotionList()

	//行动号召字段内容获取
	const action_list = ref([])
	const getActionList = () => {
		const params = {
			advertiserId: advertiser_id,
			landingType: "APP",
			platformId: 1,
		}
		getHugeInfo({ type: 'getActionList', params: JSON.stringify(params) }).then(res => {
			if (res.code == 0) {
				action_list.value = []
				const arr = JSONBIG.parse(res.data.info)
				action_list.value = arr.list
			}
		})
	}
	getActionList()


	const inputText = ref('');
	const handleEnter = () => {
		const text = inputText.value.trim();
		let arr = text.split(" ")
		arr.forEach(item => {
			if (item.length >= 2 && item.length <= 4 && advForm.value.promotion_materials.call_to_action_buttons.length < 10) {
				advForm.value.promotion_materials.call_to_action_buttons.push(item);
			}
		})
		inputText.value = '';
	};
	const removeItem = (index) => {
		advForm.value.promotion_materials.call_to_action_buttons.splice(index, 1);
	};

	const clear_call_to_action_buttons = () => {
		advForm.value.promotion_materials.call_to_action_buttons = []
	}
	
	const inputSellingPoints = ref('')
	
	const sellingPointsHandleEnter = () => {
		const text = inputSellingPoints.value.trim();
		let arr = text.split(" ")
		arr.forEach(item => {
			if (item.length >= 6 && item.length <= 9 && advForm.value.promotion_materials.product_info.selling_points.length < 10) {
				advForm.value.promotion_materials.product_info.selling_points.push(item);
			}
		})
		inputSellingPoints.value = '';
	}
	const removeSellingPointsItem = (index) => {
		advForm.value.promotion_materials.product_info.selling_points.splice(index, 1);
	};
	const clear_selling_points = () => {
		advForm.value.promotion_materials.product_info.selling_points = []
	}
	

	const addTitleMaterialList = () => {
		advForm.value.promotion_materials.title_material_list.push({ ...title_material_list_default })
	}

	const removeTitleMaterialList = (index) => {
		advForm.value.promotion_materials.title_material_list.splice(index, 1);
	}
	const reform = ref(null)
	const submitForm = () => {
		//素材计算
		advForm.value.promotion_materials.image_material_list = []
		materialImageList.value.forEach(item => {
			advForm.value.promotion_materials.image_material_list.push({
				"image_mode": "CREATIVE_IMAGE_MODE_LARGE_VERTICAL",
				"images": [
					{
						"image_id": String(item.id),
					}
				]
			})
		})
		advForm.value.promotion_materials.video_material_list = []
		//console.log(materialVideoList.value)
		materialVideoList.value.forEach(item => {
			advForm.value.promotion_materials.video_material_list.push({
				"image_mode": "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL",
				"video_id": item.videoId,
				"video_cover_id": item.material_id,
			})
		})
		materialProductList.value.forEach(item=>{
			advForm.value.promotion_materials.product_info.image_ids.push(item.id)
		})
		let params = {}
		for(let key in advForm.value){
			console.log(key)
			if(Array.isArray(advForm.value[key]) && advForm.value[key].length>0){
				params[key] = advForm.value[key]
			}else if(typeof advForm.value[key] === 'number'){
				if(advForm.value[key].length>0)
					params[key] = advForm.value[key]
			}else if(typeof advForm.value[key] === 'string'){
				if(advForm.value[key].length!="")
					params[key] = advForm.value[key]
			}else{
				params[key] = advForm.value[key]
			}	
		}
		console.log(params)
		reform.value.validate(async valid => {
			if (valid) {
				rpcGet({query:JSONBIG.stringify(params), server: "AdvService.SaveForm", platform: 1 }).then(res => {

				})
			}
		})
	}
	
	const adoptSuggestion = (value)=>{
		advForm.value.cpa_bid = value
		dialogBidSuggestVisible.value = false
	}


	defineExpose({ submitForm })
</script>

<style scoped>
	.suggest-row {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.suggest-text {
		text-align: left;
	}

	.suggest-price {
		text-align: right;
	}

	.suggest-action {
		text-align: center;
	}

	.box-card-bar {
		margin-bottom: 1vh;
		border: 1px solid var(--el-border-color);
		border-radius: 0;
		padding: 20px;
		borderRadius: var(--el-border-radius-base);
		background-color: #F2F3F5
	}

	.box-card-bar .title {
		color: #C0C4CC
	}

	.box-card-bar .info {
		margin-right: 1vh;
	}
</style>